package com.thunbu.lib_common.utils;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.provider.Settings;
import android.util.Pair;

import androidx.annotation.RequiresApi;
import androidx.core.content.FileProvider;


import com.thunbu.lib_common.function.Action;

import java.io.File;

import static android.app.Activity.RESULT_OK;

/**
 * @author wangyang
 * @since 2019/8/14
 */
public class InstallUtil {

    private static final int REQUEST_INSTALL_SETTING = 5;

    /**
     * 权限申请回调，Pair.first为Granted时的回调，Pair.second为Denied时的回调
     */
    private static Pair<Action, Action> sPair;

    public static void requestPermission(Activity context, boolean isForce, Action grantedAction, Action deniedAction) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            boolean isGranted = context.getPackageManager().canRequestPackageInstalls();
            if (!isGranted) {
//                CommonDialogUtil.createDefaultDialog(context, "安装应用需要打开未知来源权限，请去设置中开启权限", "确定", dialog -> {
//                    sPair = new Pair<>(grantedAction, deniedAction);
//                    dialog.dismiss();
//                    Uri packageURI = Uri.parse("package:" + context.getPackageName());//设置包名，可直接跳转当前软件的设置页面
//                    Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
//                    context.startActivityForResult(intent, REQUEST_INSTALL_SETTING);
//                }, "取消", dialog -> {
//                    dialog.dismiss();
//                    if (isForce) {
//                        System.exit(0);
//                    }
//                });
//                new SammboAlertDialog.Builder(context)
//                        .setCancelable(false)
//                        .setTitle(context.getString(R.string.upgrade_content))
//                        .setCancel(context.getString(R.string.cancel))
//                        .setOnCancelListener((dialog, view) -> {
//                            dialog.dismiss();
//                            if (isForce) {
//                                System.exit(0);
//                            }
//                        })
//                        .setConfirm(context.getString(R.string.confirm))
//                        .setConfirmListener((dialog, view) -> {
//                            sPair = new Pair<>(grantedAction, deniedAction);
//                            dialog.dismiss();
//                            Uri packageURI = Uri.parse("package:" + context.getPackageName());//设置包名，可直接跳转当前软件的设置页面
//                            Intent intent = new Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI);
//                            context.startActivityForResult(intent, REQUEST_INSTALL_SETTING);
//                        })
//                        .create()
//                        .show();
            } else {
                if (grantedAction != null) {
                    grantedAction.run();
                }
            }
        } else {
            if (grantedAction != null) {
                grantedAction.run();
            }
        }
    }

    public static void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == RESULT_OK && requestCode == REQUEST_INSTALL_SETTING) {
            if (sPair != null && sPair.first != null) {
                // 全部perms都满足时才执行
                sPair.first.run();
                sPair = null;
            }
        } else {
            if (sPair != null && sPair.second != null) {
                // 全部perms都满足时才执行
                sPair.second.run();
                sPair = null;
            }
        }
    }

    public static void installResult(Activity context, String path, int requestCode) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            startInstallO(context, path, requestCode);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            startInstallN(context, path, requestCode);
        } else {
            startInstall(context, path, requestCode);
        }
    }

    public static void install(Activity context, String path) {
        installResult(context, path, -1);
    }

    /**
     * android1.x-6.x
     */
    private static void startInstall(Activity context, String path, int requestCode) {
        Intent install = new Intent(Intent.ACTION_VIEW);
        install.setDataAndType(Uri.parse("file://" + path), "application/vnd.android.package-archive");
        install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        if (requestCode == -1) {
            context.startActivity(install);
        } else {
            context.startActivityForResult(install, requestCode);
        }
    }

    /**
     * android7.x
     */
    private static void startInstallN(Activity context, String path, int requestCode) {
        //参数1 上下文, 参数2 在AndroidManifest中的android:authorities值, 参数3  共享的文件
        Uri apkUri = FileProvider.getUriForFile(context, context.getApplicationInfo().packageName + ".photo_file", new File(path));
        Intent install = new Intent(Intent.ACTION_VIEW);
        //由于没有在Activity环境下启动Activity,设置下面的标签
        install.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //添加这一句表示对目标应用临时授权该Uri所代表的文件
        install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        install.setDataAndType(apkUri, "application/vnd.android.package-archive");
        if (requestCode == -1) {
            context.startActivity(install);
        } else {
            context.startActivityForResult(install, requestCode);
        }
    }

    /**
     * android8.x
     */
    @RequiresApi(api = Build.VERSION_CODES.O)
    private static void startInstallO(Activity context, String path, int requestCode) {
        startInstallN(context, path, requestCode);//安装应用的逻辑(写自己的就可以)
    }
}
